//
//  ZLDrawImageView.swift
//  ZLImageEditor
//
//  Created by 刘爽 on 2025/10/29.
//

import UIKit

class ZLDrawImageView: UIView {

    var imageView = UIImageView()

        override init(frame: CGRect) {
            super.init(frame: frame)
            addSubview(imageView)
            isUserInteractionEnabled = true
            imageView.isUserInteractionEnabled = false  // 让 imageView 不抢事件
            imageView.contentMode = .scaleAspectFit
            imageView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                imageView.topAnchor.constraint(equalTo: topAnchor),
                imageView.leadingAnchor.constraint(equalTo: leadingAnchor),
                imageView.trailingAnchor.constraint(equalTo: trailingAnchor),
                imageView.bottomAnchor.constraint(equalTo: bottomAnchor)
            ])
        }
        required init?(coder: NSCoder) { fatalError() }


    private var startPoint: CGPoint?
    var touchBegan: ((_ point: CGPoint)->Void)?
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if touches.count > 1 { return }
        guard let touch = touches.first else { return }
        let point = touch.location(in: self)
        guard bounds.contains(point) else { return }
        startPoint = point
        touchBegan?(point)
    }

    var touchMoved: ((_ point: CGPoint)->Void)?
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        if startPoint == nil { return }
        if touches.count > 1 {
            return
        }
        guard let touch = touches.first else { return }
        touchMoved?(touch.location(in: self))
    }

    var touchCancelled: ((_ point: CGPoint)->Void)?
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesCancelled(touches, with: event)
        if startPoint == nil { return }
        if touches.count > 1 {
            return
        }
        guard let touch = touches.first else { return }
        touchCancelled?(touch.location(in: self))
        startPoint = nil
    }
    
    var touchEnded: ((_ point: CGPoint)->Void)?
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesEnded(touches, with: event)
        if startPoint == nil { return }
        if touches.count > 1 {
            return
        }
        guard let touch = touches.first else { return }
        touchEnded?(touch.location(in: self))
        startPoint = nil
    }

}
